package com.qububu.db.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import com.qububu.common.position.dto.PositionInfoDto;
import com.qububu.db.dao.PositionDao;
import com.qububu.utils.ParamConverter;
import com.qububu.utils.SystemUtil;

public class PositionDaoImpl implements PositionDao {

	private JdbcTemplate jdbcTemplate;
	
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}
	
	public boolean addPositionInfo(PositionInfoDto positionInfo) {
		String sql = "insert into position set position_name = ?";
		
		int saved = jdbcTemplate.update(sql, positionInfo.getPositionName());
		
		if (saved == 1) {
			return true;
		}
		
		return false;
	}

	public List<PositionInfoDto> getPositionInfoList() {
		
		List<PositionInfoDto> positionList = null;
		String sql = "select * from position";
		
		List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql);
		
		positionList = new ArrayList<PositionInfoDto>();
		PositionInfoDto position = null;
		for (Map<String, Object> elem : resultList) {
			position = new PositionInfoDto((Long) elem.get("position_id"));
			position.setPositionName(String.valueOf(elem.get("position_name") ) );

			positionList.add(position);
		}
		
		return positionList;
	}

	public boolean modifyPositionMessage(String positionId, String positionName) {
		String sql = "update position set position_name=? where position_id=?";
		
		long rePositionId = ParamConverter.convertToLongObj(SystemUtil.decrypt(positionId));
		int updateNum = jdbcTemplate.update(sql, new Object[]{positionName, rePositionId});
		
		if (updateNum == 1) {
			return true;
		}
		
		return false;
	}

	public boolean deletePosition(String positionId) {

		String sql = "delete from position where position_id=?";
		long rePositionId = ParamConverter.convertToLongObj(SystemUtil.decrypt(positionId));
		int result = jdbcTemplate.update(sql, rePositionId);
		if (result == 1) {
			return true;
		}
		return false;
	}
}
